using System.Collections.Generic;
using Castle.Facilities.NHibernateIntegration;
using NHibernate;

namespace Tickets.Infrastructure.Repositories.NHibernate
{
	public class BaseRepository<T, IdT>
	{
		private ISessionManager _sessionManager;

		public BaseRepository(ISessionManager sessionManager)
		{
			_sessionManager = sessionManager;
		}

		public T GetById(IdT id)
		{
			using (ISession s = GetSession())
			{
				return s.Get<T>(id);
			}
		}

		public IList<T> GetAll()
		{
			using (ISession s = GetSession())
			{
				ICriteria c = s.CreateCriteria(typeof(T));
				return c.List<T>();
			}
		}

		public void Add(T aggregate)
		{
			using (ISession s = GetSession())
			{
				s.Save(aggregate);
			}
		}

		public void Save(T aggregate)
		{
			using ( ISession s = GetSession() )
			{
				s.Update(aggregate);
			}
		}

		public void Remove(T aggregate)
		{
			using ( ISession s = GetSession() )
			{
				s.Delete(aggregate);
			}
		}

		protected ISession GetSession()
		{
			// Este metodo de SessionManager devuelve una sesion nueva
			// si no exitiera una creada o devuelve la sesion activa
			return _sessionManager.OpenSession();
		}
	}
}